<?php
require_once 'EZend/Controller/AdminBaseController.php';

class Admin_LoginController extends AdminBaseController {
	public function preDispatch() {
		parent::preDispatch();
		$this->_helper->layout->setLayout('iframe');
		$this->view->headTitle()->prepend("登录");
	}
	
	public function indexAction() {
		$this->_helper->layout->setLayout('login');
		
		$from = $this->getRequest()->getParam('from');
		
		$this->view->assign('from', $from);
	}
	
	public function signinAction() {
		if (!$this->getRequest()->isPost()) return $this->showNotice('非法请求');
		
		$userName = trim($this->getRequest()->getPost('admin_name'));
		$password = trim($this->getRequest()->getPost('admin_pwd'));
		$from = urldecode($this->getRequest()->getPost('from'));
		if ('' == $userName || '' == $password) return $this->showNotice('用户名或密码为空');

		$adminUser = $this->getAdminUserService()->login($userName, $password, $this->getRequest()->getClientIp());
		if (!$adminUser) return $this->showNotice('帐号或密码错误');
		if (!$adminUser['is_valid']) return $this->showNotice('帐号已被禁用，请联系超级管理员');
		
		CurrentAdminUser::getInstance()->setUser($adminUser);
		
		$sessionId = $this->getAdminSessionService()->createSession($adminUser['user_id']);
		setcookie(SiteConfig::ADMIN_COOKIE_NAME, $sessionId, time() + SiteConfig::ADMIN_COOKIE_EXPIRE, '/', null, false, true);
		
		$this->_redirect($from ? $from : $this->view->url(array('module' => 'admin'), 'default', true));
	}
	
	protected function getAdminUserService() {
		require_once 'Models/Admin/Service/AdminServiceFactory.php';
		return AdminServiceFactory::getInstance()->createAdminUserService();
	}
	
	protected function getAdminSessionService() {
		require_once 'Models/Admin/Service/AdminServiceFactory.php';
		return AdminServiceFactory::getInstance()->createAdminSessionService();
	}
}
